package com.ruoyi.pay.aop;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.pay.LimitException;
import com.ruoyi.common.core.utils.RedisUtil;
import com.ruoyi.pay.config.RequestLimit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: Larry
 * @Date: 2024 /03 /25 / 10:30
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class LimitAOP {
    @Resource
    private  RedisUtil redisUtil ;

    public LimitAOP() {
        System.err.println("dsadasdasdasdasd");
    }

    @Pointcut("execution(public * com.ruoyi.pay.controller.*..*.*(..))")
    public void LimitPointCut(){}

    @Around("@annotation(requestLimit)")
    public Object Before(ProceedingJoinPoint proceedingJoinPoint, RequestLimit requestLimit) throws Throwable {
        log.info("进入aop中");
       int limitCount = requestLimit.count();
        System.out.println(limitCount+"limit");
       long time = requestLimit.time();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (requestAttributes != null) {
            HttpServletRequest request;
            request = requestAttributes.getRequest();
            String ip = request.getRemoteAddr();
            String url = request.getRequestURI();
            String key = "request"+ip+url;
            log.info(key);
            if(redisUtil.get(key)!=null){
                Integer count = (Integer) redisUtil.get(key);
                System.out.println(count+"==="+limitCount);
                if(count >= limitCount){
                    throw new LimitException("请不要频繁操作");
                }
                   redisUtil.incr(key,1L);
            }
            else{
                redisUtil.set(key,1,time);
            }

        }
        return proceedingJoinPoint.proceed();
    }
}
